/// <reference path="../external/jquery/jquery-3.4.1.js"/>

class Note {
    Id;
    Title; 
}

API = {
    // url: "http://39.108.181.9:5000", //部署
    url: "https://localhost:44388", //开发

    getNoteInfo: {
        url: "/api/notes/",
        sample: "/api/notes/{id}",
        result: {
            success: "{{Note}}"
        }
    },

    createNote: {
        url: "/api/notes/create",
        sample: {
            type: "POST",
            data: {
                Title: "test1"
            }
        },
        success: "{{Note}}"
    },

    updateNote: {
        url: "/api/notes/",
        sample: {
            url: "/api/notes/{id}",
            type: "PUT",
            data: "{{Note}}"
        },
        success: "204"
    }
};

var m_id;

$(function () {

    m_id = window.location.search.substr(1);
    $("#ctrl-jump-target").val(m_id);

    $.ajax({
        type: "GET",
        url: API.url + API.getNoteInfo.url + m_id,
        success: refreshNoteInfo,
        error: console.log
    });

})

function refreshNoteInfo(note) {
    $("#note-info-title").text(note.Title);
    $("#edit-title").val(note.Title);
    $("#edit-content").val(note.Content);
}

function jump() {
    location.href = "?" + $("#ctrl-jump-target").val();
}

function createNote() {
    post(API.url + API.createNote.url, 
        {
            Title: $("#ctrl-create-title").val(),
            Content: "欢迎使用笔锋"
        },
        function (state, data) {
            location.href = "?" + data.Id;
        }
    );
}

function updateNote() {

    var data = {
        Id: m_id,
        Title: $("#edit-title").val(),
        Content: $("#edit-content").val(),
    }; 
    console.log(API.url + API.updateNote.url + m_id);

    $.ajax({
        type: "PUT",
        contentType: "application/json",
        url: API.url + API.updateNote.url + m_id,
        data: JSON.stringify(data),
        success: function (response) {
            console.log(response)
            location.href = "?" + m_id;
        }
    });
    // put(API.url + API.createNote.url, { Title: $("#ctrl-create-title").val() },
    //     function (state, data) {
    //         location.href = "?" + data.Id;
    //     }
    // );
}
 
/**
 * 
 * @param {string} url 
 * @param {*} data 
 * @param {*} callback
 */
function post(url, data, callback) {
    var httpRequest = new XMLHttpRequest();//第一步：创建需要的对象
    httpRequest.open('POST', url, true); //第二步：打开连接/***发送json格式文件必须设置请求头 ；如下 - */
    httpRequest.setRequestHeader("Content-type", "application/json");//设置请求头 注：post方式必须设置请求头（在建立连接后设置请求头）var obj = { name: 'zhansgan', age: 18 };
    httpRequest.send(JSON.stringify(data));//发送请求 将json写入send中
    httpRequest.onreadystatechange = function () {//请求后的回调接口，可将请求成功后要执行的程序写在其中
        if (httpRequest.readyState == 4) {//验证请求是否发送成功
            callback(httpRequest.status, JSON.parse(httpRequest.responseText));
        }
    };
}